package frame;

import client.ClientOdImpl;
import commun.Message;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListCellRenderer;
import server._ZoneExchange;
import user.User;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Jclient.java
 *
 * Created on 4 mai 2011, 12:37:50
 */

/**
 *
 * @author qiaob
 */
public class Fclient extends javax.swing.JFrame {

    /** Creates new form Jclient */
    public Fclient() {
        this.userIcon=new javax.swing.ImageIcon(getClass().getResource("/ressources/img/boy.jpg"));
        initComponents();        
    }

    public Fclient(String UserId,final _ZoneExchange zEx, ClientOdImpl client) {
        this.zEx = zEx;
        this.client = client;
        this.initUser(UserId);
        this.model=new DefaultListModel();
        initComponents();
        this.initUsers(UserId);
        this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				try {
					zEx.logout(Fclient.this.user.getUserId());
				} catch (RemoteException e1) {
					e1.printStackTrace();
				}
				System.exit(0);
			}
		});
    }

    private void initUser(String id)
    {
      try
      {
       this.user = zEx.getUserById(id);
      }
      catch(Exception e)
      {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "Problem of connection server");
      }
      if(this.user.getSex().equals("male"))
      {
        this.userIcon=new javax.swing.ImageIcon(getClass().getResource("/ressources/img/boy.jpg"));
      }
      else
      {
       this.userIcon=new javax.swing.ImageIcon(getClass().getResource("/ressources/img/girl.jpg"));
      }

  
    }

 public void initUsers(String id)
  {
      User[] tmpUsers = null;
      try
      {
        tmpUsers=zEx.getAllFriends(id);
      }
      catch(Exception e)
      {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "Problem of connection server");
      }

      // charge the list of users

     
     this.updateUserlist(tmpUsers);

 }
 public void updateUserlist(User[] users) {
		model.removeAllElements();
		for (int i = 0; i < users.length; i++) {
			model.addElement(users[i]);
                        System.out.println(users[i].getUserName());
		}
	}
public void addUser(User user) {
		model.addElement(user);
	}
<<<<<<< .mine
public void receiveMessage(Message message) {
  
         this.setGetterMessage(message.getFromId(),true);
         if(this.listFmessage.containsKey(message.getFromId()))
         {
            ArrayList tmp=(ArrayList) this.listFmessage.get(message.getFromId());
            this.listFmessage.remove(message.getFromId());
            tmp.add(message);
            this.listFmessage.put(message.getFromId(), tmp);
         }
 else
         {
            ArrayList tmp=new ArrayList();
            this.listFmessage.put(message.getFromId(), tmp);
 }

 

}
public void setGetterMessage(String id,boolean getter)
 {
      for (int i = 0; i < model.size(); i++) {
        User tmp = (User) model.getElementAt(i);
        if (tmp.getUserId().equals(id)) {
            tmp.setGetMessage(getter);
            model.remove(i);
            model.add(i, tmp);
            break;
        }
     }

}
public void receiveOfflineMessage(){
		try {
			this.zEx.getOfflineMsg(this.user.getUserId());
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

public void quit(String message){
=======
public void receiveMessage(Message message) {
    if(this.listFmessage!=null && this.listFmessage.containsKey(message.getFromId()))
    {
          Fmessage tmp=(Fmessage)this.listFmessage.get(message.getFromId());
            tmp.displayMsg(message);  
    }
 else
    {
         this.messages.add(message);
         this.setGetterMessage(message.getFromId(),true);

    }

}
public void setGetterMessage(String id,boolean getter)
 {
      for (int i = 0; i < model.size(); i++) {
        User tmp = (User) model.getElementAt(i);
        if (tmp.getUserId().equals(id)) {
            tmp.setGetMessage(getter);
            model.remove(i);
            model.add(i, tmp);
            break;
        }
     }

}

public void quit(String message){
>>>>>>> .r42
		JOptionPane.showMessageDialog(this, message);
		System.exit(0);
	}
 class CellRenderer extends JLabel implements ListCellRenderer {
	 ImageIcon boyIcon = null;

	 ImageIcon boyGray = null;

	 ImageIcon girlIcon = null;

	 ImageIcon girlGray = null;

        public CellRenderer() {
            try {
                boyIcon=new javax.swing.ImageIcon(getClass().getResource("/ressources/img/boy1.jpg"));
                boyGray=new javax.swing.ImageIcon(getClass().getResource("/ressources/img/boy2.jpg"));
                girlIcon=new javax.swing.ImageIcon(getClass().getResource("/ressources/img/girl1.jpg"));
                girlGray=new javax.swing.ImageIcon(getClass().getResource("/ressources/img/girl2.jpg"));
			
		} catch (Exception e) {
			e.printStackTrace();
        }


	}

	// This is the only method defined by ListCellRenderer.
	// We just reconfigure the JLabel each time we're called.

	public Component getListCellRendererComponent(JList list, Object value, // value
																			// to
																			// display
			int index, // cell index
			boolean isSelected, // is the cell selected
			boolean cellHasFocus) // the list and the cell have the focus
	{
		User tmp = (User) value;
                String id=tmp.getUserId();
                String userName=tmp.getUserName();
                String sex=tmp.getSex();
		boolean online=tmp.isOnline();

		this.setText(userName + "(" + id +")");

		ImageIcon img = null;

                if(sex.equals("male"))
                {
                  if (online) {
		    img = boyIcon;
		  } else {
		    img = boyGray;
		  }
                }
                else
                {
                  if (online)
				img = girlIcon;
			else
				img = girlGray;
                }
              this.setIcon(img);
		if (isSelected) {
			setBackground(list.getSelectionBackground());
			setForeground(list.getSelectionForeground());
		} else {
			setBackground(list.getBackground());
			setForeground(list.getForeground());
		}
              this.setEnabled(list.isEnabled());
              this.setFont(list.getFont());
              if(tmp.isGetMessage())
                  this.setForeground(Color.RED);
              this.setOpaque(true);
              return this;
	}
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pUserInfo = new javax.swing.JPanel();
        lImag = new javax.swing.JLabel();
        lUserInfo = new javax.swing.JLabel();
        pListUsers = new javax.swing.JPanel();
        spListUsers = new javax.swing.JScrollPane();
        lUsers = new javax.swing.JList();
        pOther = new javax.swing.JPanel();
        bSearch = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(null);

        lImag.setIcon(this.userIcon);

        lUserInfo.setText(this.user.getUserName()+"("+this.user.getUserId()+")");

        javax.swing.GroupLayout pUserInfoLayout = new javax.swing.GroupLayout(pUserInfo);
        pUserInfo.setLayout(pUserInfoLayout);
        pUserInfoLayout.setHorizontalGroup(
            pUserInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pUserInfoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lImag, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addComponent(lUserInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(40, Short.MAX_VALUE))
        );
        pUserInfoLayout.setVerticalGroup(
            pUserInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pUserInfoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pUserInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lImag, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE)
                    .addComponent(lUserInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        getContentPane().add(pUserInfo);
        pUserInfo.setBounds(0, 0, 220, 60);

        lUsers.setModel(this.model);
        lUsers.setCellRenderer(new CellRenderer());
        lUsers.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lUsersMouseClicked(evt);
            }
        });
        spListUsers.setViewportView(lUsers);

        javax.swing.GroupLayout pListUsersLayout = new javax.swing.GroupLayout(pListUsers);
        pListUsers.setLayout(pListUsersLayout);
        pListUsersLayout.setHorizontalGroup(
            pListUsersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(spListUsers, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
        );
        pListUsersLayout.setVerticalGroup(
            pListUsersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(spListUsers, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE)
        );

        getContentPane().add(pListUsers);
        pListUsers.setBounds(0, 60, 220, 420);

        bSearch.setText("Research");

        javax.swing.GroupLayout pOtherLayout = new javax.swing.GroupLayout(pOther);
        pOther.setLayout(pOtherLayout);
        pOtherLayout.setHorizontalGroup(
            pOtherLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pOtherLayout.createSequentialGroup()
                .addContainerGap(124, Short.MAX_VALUE)
                .addComponent(bSearch)
                .addGap(19, 19, 19))
        );
        pOtherLayout.setVerticalGroup(
            pOtherLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pOtherLayout.createSequentialGroup()
                .addContainerGap(26, Short.MAX_VALUE)
                .addComponent(bSearch)
                .addContainerGap())
        );

        getContentPane().add(pOther);
        pOther.setBounds(0, 480, 220, 60);

        pack();
    }// </editor-fold>//GEN-END:initComponents

<<<<<<< .mine
    private void lUsersMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lUsersMouseClicked
        // TODO add your handling code here:
   if (evt.getClickCount() == 2) {
     JList users = (JList) evt.getSource();
     int index = users.locationToIndex(evt.getPoint());
     DefaultListModel modeltmp=(DefaultListModel)users.getModel();
     User tmp = (User) model.getElementAt(index);
     Fmessage fmessage;
      if(tmp.isGetMessage())
      {
           ArrayList list=(ArrayList) this.listFmessage.get(tmp.getUserId());

           fmessage=new Fmessage(this.zEx,list,this.user.getUserId(),tmp.getUserId());
           this.setGetterMessage(tmp.getUserId(),false);
      }
 else
      {
         fmessage =new Fmessage(this.zEx,null,this.user.getUserId(),tmp.getUserId());
         System.out.println("not messages");
 }
     
     fmessage.setVisible(true);
   }

    }//GEN-LAST:event_lUsersMouseClicked

=======
    private void lUsersMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lUsersMouseClicked
        // TODO add your handling code here:
   if (evt.getClickCount() == 2) {
     JList users = (JList) evt.getSource();
     int index = users.locationToIndex(evt.getPoint());
     DefaultListModel modeltmp=(DefaultListModel)users.getModel();
     User tmp = (User) model.getElementAt(index);

       if(this.listFmessage!=null && this.listFmessage.containsKey(tmp.getUserId()))
       {


       }
       else
       {
            Fmessage fmessage=new Fmessage(this.zEx,this.user.getUserId(),tmp.getUserId());
            fmessage.setVisible(true);
            this.listFmessage.put(tmp.getUserId(), fmessage);
       }


   }

    }//GEN-LAST:event_lUsersMouseClicked

>>>>>>> .r42
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Fclient().setVisible(true);
            }
        });
    }
<<<<<<< .mine

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bSearch;
    private javax.swing.JLabel lImag;
    private javax.swing.JLabel lUserInfo;
    private javax.swing.JList lUsers;
    private javax.swing.JPanel pListUsers;
    private javax.swing.JPanel pOther;
    private javax.swing.JPanel pUserInfo;
    private javax.swing.JScrollPane spListUsers;
    // End of variables declaration//GEN-END:variables


    private _ZoneExchange zEx;
    private ClientOdImpl  client;
    
    private ImageIcon userIcon =null;
    private User user=null;
    private DefaultListModel model=null;

     private ArrayList<Message> messages=null ;
     private Hashtable listFmessage=null;

    
}
=======

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bSearch;
    private javax.swing.JLabel lImag;
    private javax.swing.JLabel lUserInfo;
    private javax.swing.JList lUsers;
    private javax.swing.JPanel pListUsers;
    private javax.swing.JPanel pOther;
    private javax.swing.JPanel pUserInfo;
    private javax.swing.JScrollPane spListUsers;
    // End of variables declaration//GEN-END:variables


    private _ZoneExchange zEx;
    private ClientOdImpl  client;
    
    private ImageIcon userIcon =null;
    private User user=null;
    private DefaultListModel model=null;

     private ArrayList<Message> messages=null ;
     private Hashtable listFmessage=null;
}
>>>>>>> .r42
